﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Coffee_Restaurant.DAL;
using Coffee_Restaurant.Database;
using Coffee_Restaurant.Forms.Items;
using MetroFramework;

namespace Coffee_Restaurant.Forms.DinnerMenus
{
    public partial class ManagerDinnerMenus : Form
    {
        private string GroupNameSelected { get; set; }
        private string DinnerMenuIdSelect { get; set; }

        List<DataGridViewRow> _listNewRows;
        public ManagerDinnerMenus()
        {
            InitializeComponent();
        }

        void itemEdit_BtnEdit()
        {
            LoadDinnerMenu(null);
        }

        //add new node tree
        public void itemCategoryAdd_BtnAdd(string key, string name)
        {
            try
            {
                if (name != null && key != null)
                {
                    treeViewDinnerMenuCategory.Nodes.Add(key, name + " (0)");
                    TreeNode[] node = treeViewDinnerMenuCategory.Nodes.Find(key, true);
                    //load treeview
                    treeViewDinnerMenuCategory.SelectedNode = node[0];
                    var font = new Font(treeViewDinnerMenuCategory.Font, FontStyle.Underline);
                    treeViewDinnerMenuCategory.SelectedNode.NodeFont = font;
                }
            }
            catch (Exception)
            {

            }
        }

        private void ManagerItems_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'coffeeRestaurantDataSet.DinnerMenuCategories' table. You can move, or remove it, as needed.
            this.dinnerMenuCategoriesTableAdapter.Fill(this.coffeeRestaurantDataSet.DinnerMenuCategories);
            // TODO: This line of code loads data into the 'coffeeRestaurantDataSet.DinnerMenus' table. You can move, or remove it, as needed.
            // TODO: This line of code loads data into the 'coffeeRestaurantDataSet.ItemUnits' table. You can move, or remove it, as needed.
            this.itemUnitsTableAdapter.Fill(this.coffeeRestaurantDataSet.ItemUnits);
            // TODO: This line of code loads data into the 'coffeeRestaurantDataSet.sp_DinnerMenuCategories' table. You can move, or remove it, as needed.
            LoadCategoryDinners();
        }

        public void LoadCategoryDinners()
        {
            using (var db = new DatabaseEntities())
            {
                var model = db.sp_DinnerMenuCategories().ToList();
                var sumCount = db.DinnerMenus.Count();
                treeViewDinnerMenuCategory.Nodes.Clear();
                treeViewDinnerMenuCategory.Nodes.Add(null, "Tất cả (" + sumCount + ")");
                foreach (var itemc in model)
                {
                    treeViewDinnerMenuCategory.Nodes.Add(itemc.Name, itemc.Name + " (" + itemc.CountItems + ")");
                }
            }
        }

        /// <summary>
        /// event select danh muc thi se load du lieu tuong ung
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeViewCategory_AfterSelect(object sender, TreeViewEventArgs e)
        {
            GroupNameSelected = treeViewDinnerMenuCategory.Nodes[e.Node.Index].Name;
            if (string.IsNullOrEmpty(GroupNameSelected))
                LoadDinnerMenu(null);
            else
                LoadDinnerMenu(GroupNameSelected);

        }


        public void LoadDinnerMenu(string id)
        {
            using (var db = new DatabaseEntities())
            {
                //clear trc khi load
                dataGridViews.Rows.Clear();
                //mac dinh la load tat ca
                var model = db.DinnerMenus.ToList();
                if (id != null)
                {
                    //neu truyen vao id thi load theo id
                    model = db.DinnerMenus.Where(t => t.GroupName == id).ToList();
                }
                for (int i = 0; i < model.Count; i++)
                {
                    var item = model[i];
                    var row = new object[dataGridViews.ColumnCount];
                    row[0] = item.DinnerMenuId;
                    row[1] = item.Name;
                    row[2] = item.Code;
                    row[3] = item.Unit;
                    row[4] = item.Price;
                    row[5] = item.Price2;
                    row[6] = item.Price3;
                    row[7] = item.Tag;
                    row[8] = item.GroupName;
                    dataGridViews.Rows.Insert(i, row);
                }
                dataGridViews.ClearSelection(); // disable auto selected row
            }

        }


        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        //esc to exit
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.F5)
            {
                LoadDinnerMenu(null);
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void toolStripMenuReloadArea_Click(object sender, EventArgs e)
        {
            LoadCategoryDinners();
        }

        #region rightmenuItems
        private void toolStripMenuItemLoadItems_Click(object sender, EventArgs e)
        {
            LoadDinnerMenu(null);
        }

        private void toolStripMenuItemAddItem_Click(object sender, EventArgs e)
        {
            dataGridViews.AllowUserToAddRows = true;
            EnabledBtnSave();
        }

        private void toolStripMenuItemDelete_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(DinnerMenuIdSelect))
            {
                DialogResult dialogResult = CustomMessageBox.Show("Bạn chắc chắn muốn xóa món này", "", "confirm", MetroColorStyle.Default);
                if (dialogResult == DialogResult.Yes)
                {
                    var dinnerMenuDa = new DinnerMenuDa();
                    if (dinnerMenuDa.Delete(Int32.Parse(DinnerMenuIdSelect)) > 0)
                    {
                        LoadCategoryDinners();
                        LoadDinnerMenu(null);
                    }
                }

            }
            else
            {
                CustomMessageBox.Show("Bạn chưa chọn món cần xóa", "", "alert", MetroColorStyle.Default);
            }
        }

        private void toolStripMenuItemEdit_Click(object sender, EventArgs e)
        {
            CustomMessageBox.Show("Kích chọn vào ô bạn muốn sửa và nhập dữ liệu mới", "", "alert", MetroColorStyle.Default);
        }

        #endregion

        /// <summary>
        /// select ItemId for edit and delete
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewItems_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //select header column thi index = -1 => exception
            if (e.RowIndex >= 0)
            {
                //DinnerMenuIdSelect = dataGridViews.Rows[e.RowIndex].Cells["ItemId"].Value.ToString();
            }
        }

        private void dataGridViews_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Debug.WriteLine("row added");
            if (dataGridViews.Rows[e.RowIndex].Cells["DinnerMenuId"].Value == null)
            {
                dataGridViews.Rows[e.RowIndex].Tag = "NewRow";

            }
        }

        private void dataGridViews_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            Debug.WriteLine("validating cell");
            if (e.FormattedValue.ToString().Length > 0)
            {
                //validate price
                if (dataGridViews.Columns[e.ColumnIndex].Name.Contains("Price"))
                {
                    e.Cancel = !IsDecimals(e.RowIndex, e.FormattedValue.ToString()); // neu dung la false
                }
                else
                {
                    e.Cancel = !IsValidLength(e.RowIndex, e.FormattedValue.ToString()); // neu dung la false
                }
            }
            else
            {
                e.Cancel = false;
            }

        }

        public bool IsDecimals(int rowIndex, string inputData)
        {
            const string pattern = @"\d+";
            const RegexOptions regexOptions = RegexOptions.Singleline;
            var regex = new Regex(pattern, regexOptions);
            if (regex.IsMatch(inputData))
            {
                dataGridViews.Rows[rowIndex].ErrorText = null;
                return true;
            }
            dataGridViews.Rows[rowIndex].ErrorText = "Dữ liệu nhập vào là dạng số.";
            return false;
        }

        public bool IsString(int rowIndex, string inputData)
        {
            const string pattern = @"^[a-zA-Z0-9\s]+$";
            const RegexOptions regexOptions = RegexOptions.Singleline;
            var regex = new Regex(pattern, regexOptions);
            if (regex.IsMatch(inputData))
            {
                dataGridViews.Rows[rowIndex].ErrorText = null;
                return true;
            }
            dataGridViews.Rows[rowIndex].ErrorText = "Dữ liệu nhập vào là ký tự và số.";
            return false;
        }


        public bool IsValidLength(int rowIndex, string inputData)
        {
            if (inputData.Length > 0)
            {
                dataGridViews.Rows[rowIndex].ErrorText = null;
                return true;
            }
            dataGridViews.Rows[rowIndex].ErrorText = "Dữ liệu nhập vào là ký tự và số.";
            return false;
        }


        private void dataGridViews_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //flag for editing
            if (dataGridViews.Rows[e.RowIndex].Cells["DinnerMenuId"].Value != null)
            {
                dataGridViews.Rows[e.RowIndex].Tag = "EditRow";

            }
            Debug.WriteLine("end edit cell");
            if (dataGridViews.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null && !string.IsNullOrEmpty(dataGridViews.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()))
            {
                //format display
                if (dataGridViews.Columns[e.ColumnIndex].Name.Contains("Price"))
                {
                    string inputData = dataGridViews.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                    dataGridViews.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = String.Format("{0:0,0}", decimal.Parse(inputData));
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            dataGridViews.AllowUserToAddRows = true;
            EnabledBtnSave();
        }

        public void EnabledBtnSave()
        {
            btnSave.Enabled = true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            dataGridViews.AllowUserToAddRows = false;
            _listNewRows = new List<DataGridViewRow>();
            foreach (DataGridViewRow row in dataGridViews.Rows)
            {
                //update
                if (row.Tag != null && row.Tag.ToString() == "EditRow" && row.Cells["DinnerMenuId"].Value != null)
                {
                    Debug.WriteLine("update record");
                    var dinnerMenu = new DinnerMenu();
                    dinnerMenu.DinnerMenuId = int.Parse(row.Cells["DinnerMenuId"].Value.ToString());
                    if (row.Cells["NameDinnerMenu"].Value != null)
                        dinnerMenu.Name = row.Cells["NameDinnerMenu"].Value.ToString();
                    if (row.Cells["Code"].Value != null)
                        dinnerMenu.Code = row.Cells["Code"].Value.ToString();
                    if (row.Cells["Unit"].Value != null)
                        dinnerMenu.Unit = row.Cells["Unit"].Value.ToString();
                    if (row.Cells["Price"].Value != null)
                        dinnerMenu.Price = decimal.Parse(row.Cells["Price"].Value.ToString());
                    if (row.Cells["Price2"].Value != null)
                        dinnerMenu.Price2 = decimal.Parse(row.Cells["Price2"].Value.ToString());
                    if (row.Cells["Price3"].Value != null)
                        dinnerMenu.Price3 = decimal.Parse(row.Cells["Price3"].Value.ToString());
                    if (row.Cells["GroupName"].Value != null)
                        dinnerMenu.GroupName = row.Cells["GroupName"].Value.ToString();
                    dinnerMenu.Status = true;
                    dinnerMenu.Datetime = DateTime.Now;
                    DinnerMenuDa.InsertUpdate(dinnerMenu);
                }
                //add new
                if (row.Tag != null && row.Tag.ToString() == "NewRow")
                {
                    var dinnerMenu = new DinnerMenu();
                    if (row.Cells["NameDinnerMenu"].Value != null)
                        dinnerMenu.Name = row.Cells["NameDinnerMenu"].Value.ToString();
                    if (row.Cells["Code"].Value != null)
                        dinnerMenu.Code = row.Cells["Code"].Value.ToString();
                    if (row.Cells["Unit"].Value != null)
                        dinnerMenu.Unit = row.Cells["Unit"].Value.ToString();
                    if (row.Cells["Price"].Value != null)
                        dinnerMenu.Price = decimal.Parse(row.Cells["Price"].Value.ToString());
                    if (row.Cells["Price2"].Value != null)
                        dinnerMenu.Price2 = decimal.Parse(row.Cells["Price2"].Value.ToString());
                    if (row.Cells["Price3"].Value != null)
                        dinnerMenu.Price3 = decimal.Parse(row.Cells["Price3"].Value.ToString());
                    if (row.Cells["GroupName"].Value != null)
                        dinnerMenu.GroupName = row.Cells["GroupName"].Value.ToString();
                    dinnerMenu.Status = true;
                    dinnerMenu.Datetime = DateTime.Now;
                    if (DinnerMenuDa.InsertUpdate(dinnerMenu) > 0)
                    {
                        LoadCategoryDinners();
                        LoadDinnerMenu(null);
                    }
                }
            }
        }

        //select row to delete
        private void dataGridViews_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            //select header column thi index = -1 => exception
            if (e.RowIndex >= 0)
            {
                DinnerMenuIdSelect = dataGridViews.Rows[e.RowIndex].Cells["DinnerMenuId"].Value.ToString();
            }
        }
    }
}
